﻿#include "LoginDialog.h"
#include "src/bend/man/mandb.h"
#include <QCompleter>
#include <QDebug>
#include <QMouseEvent>
#include <QPushButton>
LoginDialog::LoginDialog(QWidget* parent)
    : QDialog(parent)
{
    ui.setupUi(this);
    setWindowFlags(Qt::CustomizeWindowHint);
    QPixmap pix(":/icon/resource/icon/qt.png");
    ui.logo_label->setPixmap(pix.scaled(ui.logo_label->size()));
    ui.sectedKey_lineEdit->installEventFilter(this);

    ui.title_label->setProperty("style", "h3");
    ui.loginNameLabel->setProperty("style", "h4");
    ui.sectetIdLabel->setProperty("style", "h4");
    ui.sectetKeyLabel->setProperty("style", "h4");
    ui.remarkLabel->setProperty("style", "h4");
    ui.close_btn->setProperty("style", "h4");
    ui.login_btn->setProperty("style", "h4");
    connect(ui.login_btn, &QPushButton::clicked, this, &LoginDialog::OnLoginBtn_clicked);
    connect(ui.close_btn, &QPushButton::clicked, this, &LoginDialog::OnCloseBtn_clicked);
}

LoginDialog::~LoginDialog() {}

void LoginDialog::updateLoginInfo()
{
    QStringList words     = MDB->loginNameList();
    QCompleter* completer = new QCompleter(words);
    ui.loginNameLineEdit->setCompleter(completer);
    connect(completer,
            static_cast<void (QCompleter::*)(const QString&)>(&QCompleter::activated),
            this,
            [&](const QString& name) {
                LoginInfo info = MDB->loginInfoByName(name);
                ui.sectetId_lineEdit->setText(info.secret_id);
                ui.sectedKey_lineEdit->setText(info.secret_key);
                ui.remarkLineEdit->setText(info.remark);
                ui.checkSessionCheckBox->setChecked(true);
            });
}

void LoginDialog::mousePressEvent(QMouseEvent* event)
{
    if (event->button() == Qt::LeftButton) { m_start = event->pos(); }
    QDialog::mousePressEvent(event);
}

void LoginDialog::mouseMoveEvent(QMouseEvent* event)
{
    if (event->buttons() & Qt::LeftButton) {
        QPoint targetPos = event->pos() - m_start + pos();
        this->move(targetPos);
    }
    QDialog::mouseMoveEvent(event);
}

bool LoginDialog::eventFilter(QObject* watched, QEvent* event)
{
    if (watched == ui.sectedKey_lineEdit) {
        if (event->type() == QEvent::KeyPress) {
            QKeyEvent* kEvent = static_cast<QKeyEvent*>(event);
            if (kEvent->modifiers() == Qt::ControlModifier) {
                if (kEvent->key() == Qt::Key_C || kEvent->key() == Qt::Key_V) { return true; }
            }
        }
    }
    return false;
}
void LoginDialog::OnCloseBtn_clicked() {}
void LoginDialog::OnLoginBtn_clicked()
{
    if (ui.checkSessionCheckBox->isChecked()) {
        MDB->saveLoginInfo(ui.loginNameLineEdit->text(),
                           ui.sectetId_lineEdit->text(),
                           ui.sectedKey_lineEdit->text(),
                           ui.remarkLineEdit->text());
    }
    else {
        MDB->removeLoginInfo(ui.sectetId_lineEdit->text());
    }
    updateLoginInfo();
    accept();
}